import {defineComponent, reactive, onBeforeUnmount, provide, inject, getCurrentInstance} from 'vue';
import { designComponent } from '@/use/designComponent';

interface AppRoute {
  path?: string,
  hash?: string,
  param?: { [k: string]: string }
}

export const AppNavigator = designComponent({
  name:'app-navigator',
  props:{
    defaultPath: {
      type: String,  // 当没有路径时,默认显示的页面
      required: true
    }
  },
  provideRefer: true,
  setup({props, setupContext}){
    const defaultRoute = {path: props.defaultPath};
    let currentRoute  = ensureRoute(getRoute(), defaultRoute);

    const state = reactive({
      route: currentRoute
    })

    const utils = {
      reset: () => {
        state.route = ensureRoute(getRoute(), defaultRoute);
      }
    }
    const handler = {
      hashchange: () => utils.reset()
    }
    const methods = {
      go: (path: string) => {
        window.location.hash = encodeURIComponent(path);
      }
    }

    window.addEventListener('hashchange', handler.hashchange);
    onBeforeUnmount(() => window.removeEventListener('hashchange', handler.hashchange));

    const refer = {
      state,
      methods
    }

    return {
      render: () => {
        return !!setupContext.slots.default ? setupContext.slots.default() : null;
      },
      refer
    }
  }
})

export function ensureRoute(route:null|''|AppRoute,defaultRoute:AppRoute):AppRoute{
  if (!route || !route.path) {
    return defaultRoute;
  }
  return route;
}

// /xxx-ui/#button#基本用法 ---> {path:'button',hash:'基本用法'}
function getRoute(): AppRoute | null {
  let locationHash = window.location.hash;

  console.log('getRoute --- window.location.hash: ',window.location.hash);
  if(!locationHash) return null;

  if (locationHash.charAt(0) === '#') {
    locationHash = locationHash.slice(1);
  }

  if(!locationHash) return null;

  const [path, hash] = (decodeURIComponent(locationHash)).split('#'); // /xxx-ui/#button#基本用法 ---> ['button','基本用法']
  return {
    path,hash
  }

//关于判空
//console.log(''.slice(1)===''); //true
// console.log(decodeURIComponent('')===''); //true
// console.log(decodeURIComponent('').split('#')); //['']
}

